package com.bckj.fastboot.iot.data.mongo.repository;

import com.bckj.fastboot.core.extra.mongo.AbstractMongoRepository;
import com.bckj.fastboot.core.extra.mongo.MongoOps;
import com.bckj.fastboot.core.lang.model.PageResult;
import com.bckj.fastboot.iot.common.dto.query.IotDeviceStatusRecordQuery;
import com.bckj.fastboot.iot.common.dto.request.IotDeviceStatusRecordRequest;
import com.bckj.fastboot.iot.common.dto.response.IotDeviceStatusRecordResponse;
import com.bckj.fastboot.iot.common.repository.IotDeviceStatusRecordRepository;
import com.bckj.fastboot.iot.data.mongo.convert.IotDeviceStatusRecordConvert;
import com.bckj.fastboot.iot.data.mongo.entity.IotDeviceStatusRecord;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * IotDeviceStatusRecordRepositoryImpl
 *
 * @author wfc
 **/
@Repository
public class IotDeviceStatusRecordRepositoryImpl
    extends AbstractMongoRepository<IotDeviceStatusRecord, Long>
        implements IotDeviceStatusRecordRepository {

    private final IotDeviceStatusRecordConvert iotDeviceStatusRecordConvert;

    public IotDeviceStatusRecordRepositoryImpl(
            MongoOps mongoOps,
            IotDeviceStatusRecordConvert iotDeviceStatusRecordConvert
            ) {
        super(mongoOps, IotDeviceStatusRecord.class, "iot_device_status_record");
        this.iotDeviceStatusRecordConvert = iotDeviceStatusRecordConvert;
    }


    @Override
    public List<IotDeviceStatusRecordResponse> findList(IotDeviceStatusRecordQuery query) {
        return find(buildQuery(query), IotDeviceStatusRecordResponse.class);
    }

    @Override
    public PageResult<IotDeviceStatusRecordResponse> page(Pageable page, IotDeviceStatusRecordQuery query) {
        return page(page, buildQuery(query), IotDeviceStatusRecordResponse.class);
    }

    @Override
    public boolean save(IotDeviceStatusRecordRequest request) {
        var entity = iotDeviceStatusRecordConvert.toEntity(request);
        return save(entity);
    }

    private Query buildQuery(IotDeviceStatusRecordQuery query) {
        Criteria criteria = Criteria.where("devCode").is(query.getDevCode());
        return Query.query(criteria);
    }
}
